package com.exsun.gateway.jt809.handler;

import com.exsun.gateway.jt809.codec.protocol.Jt809Encode;
import com.exsun.gateway.jt809.common.LinkType;
import com.exsun.gateway.jt809.common.LinkMgr;
import com.exsun.gateway.jt809.config.NettyClientConfig;
import exsun.jt808.data.config.jt809.Jt809MsgIdConfig;
import exsun.jt808.data.jt809_data.linkmanage.UpConnectReq;
import exsun.jt808.data.jt809_data.video.main.UpAuthorizeMsgStartup;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 809网关kafka消息订阅处理
 */
@Service
public class SendMgrHandler {

    @Autowired
    public Jt809Encode jt809Encode;

    private static Logger logger = LoggerFactory.getLogger(SendMgrHandler.class);

    /**
     * 主链路登录请求
     */
    public void upConnectReq(NettyClientConfig nettyClientConfig){
        UpConnectReq data = new UpConnectReq(nettyClientConfig.getUserid(),
                nettyClientConfig.getPassword(),nettyClientConfig.getDownLinkIp(),
                nettyClientConfig.getDownLinkPort());
        byte[] bytes = jt809Encode.upConnectReq(data);
        LinkMgr.push2FixedChannel(Jt809MsgIdConfig.UP_CONNECT_REQ, bytes, LinkType.MASTER);

        logger.info("主链路登录请求");
    }
//    /**
//     *登陆应答测试
//     */
//    public void upConnectReq1(NettyClientConfig nettyClientConfig){
//        try {
//            UpConnectReq data = new UpConnectReq(nettyClientConfig.getUserid(),
//                    nettyClientConfig.getPassword(), nettyClientConfig.getDownLinkIp(),
//                    nettyClientConfig.getDownLinkPort());
//            byte[] bytes = jt809Encode.upConnectReq(data);
//            LinkMgr.push2FixedChannel(Jt809MsgIdConfig.UP_CONNECT_REQ, bytes, 0);
//            logger.info("主链路登录请求");
//            Thread.sleep(4000);
//            UpConnectRsp data1 = new UpConnectRsp();
//            data1.setResult(0);
//            data1.setCheckCode(123456);
//            byte[] bytes1 = jt809Encode.upConnectRsp(data1);
//            LinkMgr.push2FixedChannel(Jt809MsgIdConfig.UP_CONNECT_RSP, bytes1, 0);
//            logger.info("主链路登录应答");
//            Thread.sleep(4000);
//        }
//        catch (Exception ex)
//        {
//        }
//
//    }
    /**
     * 主链路连接保持请求
     * @param channel
     */
    public void linkHeart(Channel channel){

        byte[] bytes = jt809Encode.upLinkTestReq();
        LinkMgr.push2FixedChannel(Jt809MsgIdConfig.UP_LINKTEST_REQ, bytes, channel);
        logger.info("主链路连接保持请求");
    }

    /**
     * 时效口令上传
     */
    public void agingPassword(UpAuthorizeMsgStartup data){
        byte[] bytes = jt809Encode.upAuthorizeMsgStartup(data);
        boolean result = LinkMgr.push2FixedChannel(Jt809MsgIdConfig.UP_AUTHORIZE_MSG, bytes, LinkType.MASTER);
        logger.info("时效口令上传：{}",result?"成功":"失败");
    }


}